package com.thingple.web.bridge.reader;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

import com.thingple.eye.ActionResultListener;
import com.thingple.h5.bridge.Bridge;
import com.thingple.h5.bridge.BridgeConfig;
import com.thingple.h5.bridge.JsInvokeHandler;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 读卡后,处理
 * Created by lism on 2017/8/18.
 */

class ReadCardListenerV2 implements ActionResultListener {

    private WebView webView;

    private Bridge jsBridge;

    private String funcName;

    ReadCardListenerV2(WebView webView, Bridge jsBridge) {

        this.webView = webView;
        this.jsBridge = jsBridge;
    }

    public void setFuncName(String funcName) {
        this.funcName = funcName;
    }

    private void onReadCard(String tid, String epc, String user) {
        if (funcName != null) {
            BridgeConfig bridgeConfig = jsBridge.getClass().getAnnotation(BridgeConfig.class);
            if (bridgeConfig == null) {
                return;
            }
            Map<String, String> paramMap = new HashMap<>();
            if (tid != null) {
                paramMap.put("tid", tid);
            }
            if (epc != null) {
                paramMap.put("epc", epc);
            }
            if (user != null) {
                paramMap.put("user", user);
            }

            JsInvokeHandler jsInvokeHandler = new JsInvokeHandler(webView);
            jsInvokeHandler.module("window")
                    .function(funcName)
                    .params(paramMap)
                    .invoke();
        }
    }

    @Override
    public void onResponse(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                String tid = bundle.getString("TID");
                String epc = bundle.getString("EPC");
                String user = bundle.getString("USER");
                onReadCard(tid, epc, user);
            }
        }
    }

}
